package com.pingan.project.autosendsms;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.security.auth.login.LoginException;

/**
 * Created by hua on 2016/11/23.
 */

public class SmsReciver extends BroadcastReceiver {
    private static final String TAG = SmsReciver.class.getSimpleName();
    public static final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        Log.e(TAG, "onReceive-----------");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showNotice(mContext);
            }
        }, 2000);

        Bundle bundle = intent.getExtras();
        SmsMessage msg;
        if (null != bundle) {
            Object[] smsObj = (Object[]) bundle.get("pdus");
            for (Object object : smsObj) {
                msg = SmsMessage.createFromPdu((byte[]) object);
                String msgBody = msg.getDisplayMessageBody();
                String number = msg.getOriginatingAddress();
                long time = msg.getTimestampMillis();
                //
//                query(context, msgBody, time);
                List<SmSBean> smsList = ShareUtil.getInstance(context).getSMS();
                for (SmSBean bean : smsList) {
                    if (!TextUtils.isEmpty(msgBody) && msgBody.contains(bean.key)) {
//                        query(context,msgBody,time);
                        sendSms(bean.content, context, number, time, msgBody);
                        break;
                    }
                }
            }
        }
    }

    private void sendSms(String msg, Context context, String number, long time, String msgBody) {
        SmsManager SM = SmsManager.getDefault();
        Class SMClass = SmsManager.class; //通过反射查到了SmsManager有个叫做mSubId的属性
        // create the sentIntent parameter
        Intent sentIntent = new Intent(SENT_SMS_ACTION);

        Field field = null;
        try {
            field = SMClass.getDeclaredField("mSubId");
            field.setAccessible(true);
            try {
                int smsType = ShareUtil.getInstance(context).getSMSType();
                field.set(SM, smsType);
                //1.136
                //0.155
                sentIntent.putExtra("address", number);
                sentIntent.putExtra("msg", msg);
                sentIntent.putExtra("time", time);
                sentIntent.putExtra("msgBody", msgBody);
                PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent,
                        0);
                SM.sendTextMessage(number, null, msg, sentPI, null);
                Log.e("TAG", "onCreate: sendTextMessage");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private void showNotice(Context context) {
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        int notifyID = 1;
        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context)
                .setContentTitle("New Message")
                .setVibrate(new long[]{500L, 200L, 200L, 500L})
                .setSmallIcon(R.drawable.coffe_red).setPriority(Notification.PRIORITY_MAX);

        int numMessages = 0;
        mNotifyBuilder.setContentText("You've received new messages.")
                .setNumber(++numMessages);
        mNotificationManager.notify(
                notifyID,
                mNotifyBuilder.build());
    }
}
